package com.iseastar.guojiang.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.shouhuobao.station.R;
import com.zbar.camera.CameraManager;
import com.zbar.client.CaptureActivity;

import droid.frame.activity.title.TitleMgr;
import droid.frame.activity.title.TitleRes;
import droid.frame.utils.lang.Str;
import droid.frame.view.TextWatcherExt;

/**
 * 裹将app用到的扫码界面
 *
 * @author coffee<br>
 *         2015-3-24下午4:22:34
 */
public class AppCaptureActivity extends CaptureActivity {

    /**
     * 当前闪光灯是否打开
     */
    private boolean isOpenFlash;
    /**
     * 顶部的文字提示
     */
    private TextView mTopTip;

    private Button mEditButton;
    private EditText mEditText;
    /**
     * 是否是驿站
     */
    private boolean isStation;
    private String action;

    @Override
    public void onCreate(Bundle icicle) {
        action = getIntent().getAction();
        if (Intents.station_scan_for_input.equals(action)) {
            setLayout(R.layout.capture_input_parcel, true);
        }
        // 裹将扫驿站二维码 -- 获取所有包裹列表
        else if (Intents.guojiang_for_station_parcels.equals(action)//
                // 核对包裹列表的包裹
                || Intents.guojiang_check_parcel.equals(action)) {
            setLayout(R.layout.capture_station, true);
            isStation = true;
        } // 标准上门、报价、扫码绑定
        else if (Intents.guojiang_order_bind.equals(action)) {
            setLayout(R.layout.capture_order_bind, true);
        } else {// 检验袋子编码是否正常
            setLayout(R.layout.capture, true);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(icicle);
        TitleMgr titleMgr = new TitleMgr(this);
        titleMgr.initTitle();
        final ImageView titleRightImage = (ImageView) findViewById(R.id.title_right_image);
        titleMgr.setTitle(new TitleRes[]{titleMgr.getBackTitle(), new TitleRes("扫描投递袋条形码"), new TitleRes(R.drawable.title_flashlight_on_selector, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpenFlash) {// 当前是打开的
                    // cameraManager.setTorch(false);// 关闭闪光灯
                    CameraManager.get().offLight();
                    isOpenFlash = false;
                    titleRightImage.setImageResource(R.drawable.title_flashlight_on_selector);
                } else {// 当前闪光灯是关闭的
                    // cameraManager.setTorch(true);// 打开
                    CameraManager.get().openLight();
                    isOpenFlash = true;
                    titleRightImage.setImageResource(R.drawable.title_flashlight_off_selector);
                }
            }
        })});
        //
        View titleLayout = findViewById(R.id.app_title_layout);
        TextView titleMiddle = (TextView) findViewById(R.id.title_middle_text);
        this.mTopTip = (TextView) findViewById(R.id.capture_top_tip);
        ViewGroup inputGroup = (LinearLayout) findViewById(R.id.capture_input_layout);
        // 裹将扫 驿站 -- 取包裹
        if (Intents.station_scan_for_input.equals(action)) {
            titleMiddle.setText("运单号扫描");
            mTopTip.setText("将运单条码放在扫码框内");
        } else if (Intents.guojiang_for_station_parcels.equals(action)) {
            titleLayout.setBackgroundResource(R.color.app_theme_color2);
            inputGroup.setBackgroundResource(R.color.app_theme_color2);
            titleMiddle.setText("扫描驿站二维码");
        }
        // 裹将扫驿站的包裹、扫包裹条形码、核对包裹
        else if (Intents.guojiang_check_parcel.equals(action)) {
            titleLayout.setBackgroundResource(R.color.app_theme_color2);
            inputGroup.setVisibility(View.INVISIBLE);
            titleMiddle.setText("扫描投递袋条码");
            mTopTip.setText("扫描投递袋条码，可以查看包裹详情");
            // ((ViewfinderView) getViewfinderView()).setQrcode(false);
        }
        // 驿站扫用户 -- 收包裹
        else {
            if (Intents.station_for_user_parcel.equals(action)) {
                titleLayout.setBackgroundResource(R.color.app_theme_color2);
                inputGroup.setBackgroundResource(R.color.app_theme_color2);
                findViewById(R.id.capture_input_ok).setVisibility(View.GONE);
                titleMiddle.setText("扫描投递袋条形码");
            } else {
                titleLayout.setBackgroundResource(R.color.app_theme_color);
                inputGroup.setBackgroundResource(R.color.app_theme_color);
                titleMiddle.setText("绑定条码");
            }
        }
        mEditButton = (Button) findViewById(R.id.capture_input_ok);
        if (mEditButton == null) {
            // null 不作处理
        } else {
            mEditButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback(mEditText.getText().toString());
                }
            });
        }

        mEditText = (EditText) findViewById(R.id.capture_input_edit);
        if (mEditText == null) {
            // null 不作处理
        } else {
            mEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
            // mEditText.setImeActionLabel("完成1", 1);
            // 移动光标到最后
            Editable editable = mEditText.getEditableText();
            Selection.setSelection(editable, editable.length());
            mEditText.setOnEditorActionListener(new OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    String contents = mEditText.getText().toString();
                    contents = Str.strClearEmpty(contents);
                    callback(contents);
                    return false;
                }
            });
            mEditText.addTextChangedListener(new TextWatcherExt() {
                @Override
                public void afterTextChanged(Editable editable) {
                    // if (editable.length() > 3) {
                    // setButtonEnableStyle(mEditButton, true);
                    // } else {
                    // setButtonEnableStyle(mEditButton, false);
                    // }
                    if (isStation) {
                        if (editable.length() == 10) {
                            String contents = mEditText.getText().toString();
                            callback(contents);
                        }
                    } else {
                        mEditText.removeTextChangedListener(this);
                        Str.formatBagCode(mEditText);
                        mEditText.addTextChangedListener(this);
                        if (editable.length() == 12) {
                            String contents = mEditText.getText().toString();
                            contents = Str.strClearEmpty(contents);
                            callback(contents);
                        }
                    }
                }
            });
        }

    }

    @Override
    protected boolean callback(String contents) {
        if (Intents.guojiang_for_station_parcels.equals(action)) {
            int index = contents.lastIndexOf("=");
            String result2;
            if (index > -1) {
                result2 = contents.substring(index + 1, contents.length());
            } else {
                result2 = contents;
            }
            Intent data = new Intent();
            data.putExtra("result", result2);
            setResult(RESULT_OK, data);
        } else {
            // 驿站扫码
            Intent data = new Intent();
            data.putExtra("result", contents);
            setResult(RESULT_OK, data);
        }
        finish();
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            setResult(RESULT_OK, data);
            finish();
        }
    }

    public void setButtonEnableStyle(Button button, boolean enable) {
        if (button == null) {
            return;
        }
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_btn_selector);
            button.setTextColor(getResources().getColorStateList(R.color.app_button_textcolor_selector));
        } else {
            button.setBackgroundResource(R.drawable.app_btn_disable_selector);
            button.setTextColor(getResources().getColor(R.color.app_font_2));
        }
        button.setPadding(left, top, right, bottom);
    }
}
